//
//  MySpecialSignVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/29.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "MySpecialSignVC.h"
#import "PopSignUtil.h"
#import "NWLoginRequest.h"
#import "JinXCViewController.h"

#import "EXTScope.h"

OSSClient * client;

@interface MySpecialSignVC ()

@property (nonatomic,strong) UIImageView *imgView;
/** 用此ID调用修改用户资料接口 */
@property (nonatomic, copy) NSString *changeUserInfoID;

@end

@implementation MySpecialSignVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:KwBgColor];
    self.title = @"我的签名";
    NWLoginRequest *request = [[NWLoginRequest alloc] init];
    [request  startRequestGetUserInfoWithId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ) {
            self.changeUserInfoID = result[@"id"];
        }
    }];

    [self createRightButton:@"修改" selector:@selector(changeSign)];
    [self setUpUI];
    if (self.isFirstSubmit) {
//        self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
//        self.navigationItem.hidesBackButton = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self changeSign];
            });
        });
    }
}

- (void)setUpUI
{
    CGFloat imgWid = SCREEN_WIDTH-30*2;
    _imgView = [UIImageView new];
    _imgView.backgroundColor = [UIColor whiteColor];
    [_imgView sd_setImageWithURL:[NSURL URLWithString:[NSUserDefaults retrieveObjectForKey:kUserInfo_Autograph]]];
    [self.view addSubview:_imgView];
    [_imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@30);
        make.right.equalTo(@-30);
        make.top.equalTo(@50);
        make.height.equalTo(@(imgWid*2/3));
    }];
}

- (void)uploadImageWithImage:(UIImage *)image
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddhhmmss"];
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName =  [NSString stringWithFormat:@"%@%@%@.png",kUploadImgPath,str,[Constants createUUID]];

        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        OSS_Request *request = [[OSS_Request alloc]init];
        [request uploadFileSyscToOSSWithData:imageData destinationFileName:fileName progressBlock:nil completeHandler:^(BOOL isSuccess, NSError *error, NSString *url) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (isSuccess)
            {
                //图片上传成功  开始发送请求
                dispatch_async(dispatch_get_main_queue(), ^{
                    NWLoginRequest *request = [[NWLoginRequest alloc] init];
                    [request startRequestChangeSignatureWithId:strongSelf.changeUserInfoID autograph:url.stringByRemovingPercentEncoding];
                    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                        if (succ)
                        {
                            [weakSelf showSuccAlertWithMessage:@"图片上传成功"];
                            [NSUserDefaults saveObject:url forKey:@"autograph"];
                            strongSelf->_imgView.image =image;
                            if (strongSelf.isFirstSubmit) {
//                                if ([[[UserModel getUser] isInit] isEqualToString: @"0"] && [[Singleton shareInstance].userType integerValue] == UserTypeAgency)
//                                {
//                                    JinXCViewController *jinXC = [JinXCViewController new];
//                                    jinXC.isFirstSubmit = strongSelf.isFirstSubmit;
//                                    [strongSelf.navigationController pushViewController:jinXC animated:YES];
//                                } else {
                                    [SharedApp setRootViewController];
//                                }
                            }
                            [PopSignUtil closePop];
                        } else {
                            [SVProgressHUD showErrorWithStatus:message];
                        }
                    }];
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf showHUDWithMessage:@"图片上传失败，请重试"];
                });
            }

        }];
    });

}


- (void)changeSign
{
    @weakify(self)
    [PopSignUtil getSignWithVC:nil withOk:^(UIImage *image){
        @strongify(self)
        [self uploadImageWithImage:image];
    } withCancel:^{
        [PopSignUtil closePop];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    NSLog(@"Dealloc------............");
}

@end
